package com.headwind.async.service.impl;

import com.headwind.async.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.Future;

/**
 * @author : Headwind
 * @version : 1.0
 * @date : Created in 2020/8/9
 * @description : 多任务实现类
 */
@Service
public class AsyncServiceImpl implements AsyncService {
    /**
     * 任务1
     *
     * @return 执行结果
     */
    @Async
    @Override
    public Future<String> task1() {
        System.out.println("开始执行任务一");
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(new Random().nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("任务一执行结束，耗时：" + (System.currentTimeMillis() - start) + "毫秒");
        return new AsyncResult<>("Task1");
    }

    /**
     * 任务2
     *
     * @return 执行结果
     */
    @Async
    @Override
    public Future<String> task2() {
        System.out.println("开始执行任务二");
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(new Random().nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("任务二执行结束，耗时：" + (System.currentTimeMillis() - start) + "毫秒");
        return new AsyncResult<>("Task2");
    }

    /**
     * 任务3
     *
     * @return 执行结果
     */
    @Async
    @Override
    public Future<String> task3() {
        System.out.println("开始执行任务三");
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(new Random().nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("任务三执行结束，耗时：" + (System.currentTimeMillis() - start) + "毫秒");
        return new AsyncResult<>("Task3");
    }
}
